package kr.or.javacafe.main.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Locale;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping("/")
public class IndexController {
	
	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Locale locale, Model model) {
		return "redirect:/home";
	}
	

	@RequestMapping(value = "home", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		return "home";
	}


	@RequestMapping(value = "recommand", method = RequestMethod.GET)
	public String recommand(Locale locale, Model model) {
		return "recommand";
	}


	@RequestMapping(value = "main", method = RequestMethod.GET)
	public String main(Locale locale, Model model) {
		return "main";
	}
	
	
	@RequestMapping(value = "gw", method = RequestMethod.GET)
	public String gw(@RequestParam("site") String site, Model model) {
		try {
			HttpClient httpClient = new HttpClient();
			HttpMethod method = new GetMethod(site);
			
			int status = httpClient.executeMethod(method);
			if (200 == status) {
				StringBuffer resultMessage = new StringBuffer();
				
				BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8"));
				String line;
			    while ((line = br.readLine()) != null) {
			    	resultMessage.append(line);
			    }
			    br.close();
				
			    model.addAttribute("contents", resultMessage.toString()); 
				
			}
		} catch (Exception ex) {
			model.addAttribute("contents", ex.toString()); 
		}
		
		return "gw";
	}
	
	
}
